package com.gupao.javavip.netty.push.server.processor.handler;

import com.gupao.javavip.netty.push.api.Request;
import com.gupao.javavip.netty.push.api.RequestCommand;
import com.gupao.javavip.netty.push.api.Response;
import com.gupao.javavip.netty.push.api.ResponseCode;
import com.gupao.javavip.netty.push.server.processor.PushMsgServerService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.apachecommons.CommonsLog;

import java.util.concurrent.atomic.AtomicInteger;

@CommonsLog
public class PushMsgServerHandler extends SimpleChannelInboundHandler<Request> {
    private PushMsgServerService service = new PushMsgServerService();

    private static volatile AtomicInteger counter = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Request request) throws Exception {
        if (!RequestCommand.PUSH.name().equals(request.getCommand())) {
            channelHandlerContext.fireChannelRead(request);
            return;
        }

        log.debug("收到" + request.getPushSource() + "提交的推送消息：" + request.toString());
        log.debug("累计收到消息条数：" + counter.incrementAndGet());

        service.saveMsg(request.getMsg());

        sendResponse(channelHandlerContext, request);
    }

    private void sendResponse(ChannelHandlerContext channelHandlerContext, Request request) {
        Response response = new Response();
        response.setCode(ResponseCode.SUCCESS.name());
        response.setMsg("消息[" + request.getMsg().getId() + "]提交成功！");

        channelHandlerContext.channel().writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("与客户端断开连接:" + cause.getMessage(), cause);
        ctx.close();
    }
}
